package code5;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSendFile extends Thread {

    private String str = null;

    public ServerSendFile(String str){this.str = str;}

    @Override
    public void run(){

        Socket s = null;
        DataOutputStream dos = null;
        DataInputStream dis = null;
        try {
            ServerSocket ss = new ServerSocket(1239);
            s = ss.accept();
            System.out.println("服务器准备发送文件！");

            // 对客户端发送的文件路径进行解析，得到文件名称
            String[] s1 = str.split(" ");
            String[] s2 = s1[1].split("/");
            String fileName = s2[s2.length-1];

            dos = new DataOutputStream(s.getOutputStream());
            File file = new File("F:/ServerReceivedFile/"+fileName);
            dis = new DataInputStream(new FileInputStream(file));

            byte[] barr = new byte[1024];
            int res = 0;

            while((res=dis.read(barr))!=-1){
                dos.write(barr,0,res);
                dos.flush();
            }
            System.out.println("服务器发送文件成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null!=dis){
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=dos){
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=s){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
